<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <style>
    .box {
      position: relative;
      width: 200px;
      height: 200px;
      background-color: pink;
    }
    .box span {
      position: absolute;
      left: 0;
      top: 0;
      width: 20px;
      height: 20px;
      background-color: green;
    }
  </style>
  <body>
    <div class="box">
      <span>X</span>
    </div>
    <button>关闭setTimeout</button>

    <script>
      var timer = setTimeout(function () {
        console.log("你好");
      }, 2000);

      var cont = document.querySelector(".box span");
      var box = document.querySelector(".box");
      cont.onclick = function () {
        setTimeout(function () {
          box.remove();
        }, 2000);
      };

      var btn = document.querySelector("button");
      btn.onclick = function () {
        clearTimeout(timer);
      };
    </script>
  </body>
</html>
